from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager

class UserRole(models.TextChoices):
    """用户角色枚举"""
    USER = "user", "普通用户"
    DISPATCHER = "dispatcher", "调度员"
    ADMIN = "admin", "管理员"

class CustomUserManager(BaseUserManager):
    """自定义用户管理器"""
    def create_user(self, email, password=None, **extra_fields):
        """创建普通用户"""
        if not email:
            raise ValueError("必须填写邮箱")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        """创建超级管理员（用于命令行创建初始管理员）"""
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("role", UserRole.ADMIN)
        
        if extra_fields.get("is_staff") is not True:
            raise ValueError("超级用户必须设置is_staff=True")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("超级用户必须设置is_superuser=True")
            
        return self.create_user(email, password, **extra_fields)

class CustomUser(AbstractBaseUser, PermissionsMixin):
    """自定义用户模型"""
    email = models.EmailField("邮箱", unique=True)
    full_name = models.CharField("姓名", max_length=100)
    phone = models.CharField("手机号", max_length=20, blank=True)
    role = models.CharField("角色", max_length=20, choices=UserRole.choices, default=UserRole.USER)
    is_active = models.BooleanField("是否激活", default=True)
    _is_staff = models.BooleanField("后台权限", default=False, db_column="is_staff")  # 控制Django Admin访问

    USERNAME_FIELD = "email"       # 用邮箱作为登录标识
    REQUIRED_FIELDS = ["full_name"]  # 创建用户时必须填写的字段

    objects = CustomUserManager()

    def __str__(self):
        return self.email
        
    @property
    def is_staff(self):
        """
        重写is_staff属性，使is_superuser=True的用户自动被视为staff
        """
        return self._is_staff or self.is_superuser
        
    @is_staff.setter
    def is_staff(self, value):
        """
        设置is_staff属性
        """
        self._is_staff = value
        
    def has_perm(self, perm, obj=None):
        """
        重写has_perm方法，使is_superuser=True的用户拥有所有权限
        """
        if self.is_superuser:
            return True
        return super().has_perm(perm, obj)